package com.slj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slj.comm.responce.PageResult;
import com.slj.comm.responce.R;
import com.slj.mapper.InventoryMapper;
import com.slj.model.entity.Inventory;
import com.slj.model.vo.InventoryProductVO;
import com.slj.service.InventoryService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {

    @Autowired
    private InventoryMapper inventoryMapper;

    private final LocalDateTime currentTime = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);

    @Override
    public R<String> addInventory(Inventory inventory) {
        inventory.setCreateAt(currentTime);
        inventory.setUpdateAt(currentTime);
        int result = inventoryMapper.insert(inventory);
        return result > 0 ? R.success("添加成功") : R.fail("添加失败");
    }

    @Override
    public R<String> deleteInventory(Integer id) {
        int result = inventoryMapper.deleteById(id);
        return result > 0 ? R.success("删除成功") : R.fail("删除失败");
    }

    @Override
    public R<String> updateInventory(Inventory inventory) {
        inventory.setUpdateAt(currentTime);
        int result = inventoryMapper.updateById(inventory);
        return result > 0 ? R.success("更新成功") : R.fail("更新失败");
    }

    @Override
    public R<Inventory> getInventoryById(Integer id) {
        Inventory inventory = inventoryMapper.selectById(id);
        return inventory != null ? R.success(inventory) : R.fail("未找到对应库存记录");
    }

    @Override
    public R<List<InventoryProductVO>> getInventoryPage(Integer pageNum, Integer pageSize, String productName) {
        Page<InventoryProductVO> page = new Page<>(pageNum, pageSize);
        List<InventoryProductVO  > list=inventoryMapper.selectInventoryProductPage(productName, page);
        return R.success(list);
    }

    @Override
    public R<String> adjustSafeQuantity(Integer inventoryId, Integer safeQuantity) {
        Inventory inventory = inventoryMapper.selectById(inventoryId);
        if (inventory == null) {
            return R.fail("库存记录不存在");
        }
        inventory.setSafeQuantity(safeQuantity);
        inventory.setUpdateAt(currentTime);
        int result = inventoryMapper.updateById(inventory);
        return result > 0 ? R.success("安全库存调整成功") : R.fail("安全库存调整失败");
    }

    @Override
    public void exportInventoryToExcel(HttpServletResponse response) {
        List<Inventory> inventoryList = inventoryMapper.selectList(null);

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("库存数据");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"库存ID", "商品ID", "商品名称", "库存量", "安全库存量", "最后更新时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 填充数据
            int rowNum = 1;
            for (Inventory inventory : inventoryList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(inventory.getInventoryId());
                row.createCell(1).setCellValue(inventory.getProductId());
                row.createCell(2).setCellValue(inventory.getProductName());
                row.createCell(3).setCellValue(inventory.getQuantity());
                row.createCell(4).setCellValue(inventory.getSafeQuantity());
                row.createCell(5).setCellValue(inventory.getLastUpdate().toString());
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("库存数据_" + System.currentTimeMillis() + ".xlsx", StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 写入响应流
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    @Override
    public R<String> batchUpdateInventory(List<Inventory> inventoryList) {
        int result = inventoryMapper.batchUpdate(inventoryList);
        return result > 0 ? R.success("批量更新成功") : R.fail("批量更新失败");
    }

    @Override
    public R<List<Inventory>> getInventoryBelowSafeQuantity() {
        List<Inventory> list = inventoryMapper.selectBelowSafeQuantity();
        return R.success(list);
    }

    @Override
    public R<PageResult<InventoryProductVO>> getInventoryProductPage(Integer pageNum, Integer pageSize, String productName) {
        Page<InventoryProductVO> page = new Page<>(pageNum, pageSize);
        List<InventoryProductVO> list = baseMapper.selectInventoryProductPage(productName, page);

        // 计算库存状态
        list.forEach(item -> {
            item.setStockStatus(getStockStatus(item.getQuantity(), item.getSafeQuantity()));
        });

        // Use static factory method to create PageResult
        PageResult<InventoryProductVO> pageResult = PageResult.of(page);
        return R.success(pageResult);
    }

    @Override
    public R<List<InventoryProductVO>> getInventoryProductBelowSafeQuantity() {
        List<InventoryProductVO> list = baseMapper.selectBelowSafeQuantityWithProduct();
        // 计算库存状态
        list.forEach(item -> {
            item.setStockStatus(getStockStatus(item.getQuantity(), item.getSafeQuantity()));
        });
        return R.success(list);
    }

    private String getStockStatus(Integer quantity, Integer safeQuantity) {
        if (safeQuantity == null) return "未设置安全库存";
        if (quantity >= safeQuantity * 1.5) return "库存充足";
        if (quantity >= safeQuantity) return "库存适中";
        if (quantity >= safeQuantity * 0.5) return "库存偏低";
        return "库存不足";
    }
}